﻿using System;
using NHibernate;
using TestBat.IModels.Base;
using TestBat.IModels.Factories;
using TestBat.ServiceLocator;

namespace TestBat.Models.Interceptors.Session
{
    public class SessionIntercepter : EmptyInterceptor
    {
        public SessionIntercepter(IEntityFactory entityFactory)
        {
            this.entityFactory = entityFactory;
        }

        //public ISessionFactory SessionFactory { set; get; }

        public override object Instantiate(string clazz, EntityMode entityMode, object id)
        {
            if (entityMode == EntityMode.Poco)
            {
                Type type = Type.GetType(clazz);
                if (type != null)
                {
                    var instance = entityFactory.Create(type);
                    ISessionFactory sessionFactory = DefaultServiceLocator.Get<ISessionFactory>();
                    sessionFactory.GetClassMetadata(clazz).SetIdentifier(instance, id, entityMode);

                    return instance;
                }
            }
            return base.Instantiate(clazz, entityMode, id);
        }

        public override string GetEntityName(object entity)
        {
            var markerInterface = entity as IMarker;
            if (markerInterface != null)
                return markerInterface.TypeName;
            return base.GetEntityName(entity);
        }

        protected readonly IEntityFactory entityFactory;
    }
}
